using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Comteck.Winforms.Extensions {
  /// <summary>
  /// 实现distinct(某几个字段) add by alex.lin
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <typeparam name="V"></typeparam>
  public class CommonEqualityComparer<T, V> : IEqualityComparer<T> {
    private Func<T, V> keySelector;
    private IEqualityComparer<V> comparer;

    public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer) {
      this.keySelector = keySelector;
      this.comparer = comparer;
    }

    public CommonEqualityComparer(Func<T, V> keySelector)
        : this(keySelector, EqualityComparer<V>.Default) { }

    public bool Equals(T x, T y) {
      return comparer.Equals(keySelector(x), keySelector(y));
    }

    public int GetHashCode(T obj) {
      return comparer.GetHashCode(keySelector(obj));
    }
  }
  public static class CommonFunctionExtensions {
    /// <summary>
    /// 扩展Distinct方法
    /// </summary>
    /// <typeparam name="T">源类型</typeparam>
    /// <typeparam name="V">委托返回类型（根据V类型，排除重复项）</typeparam>
    /// <param name="source">扩展源</param>
    /// <param name="keySelector">委托（执行操作）</param>
    /// <returns></returns>
    public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector) {
      return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
    }

    /// <summary>
    /// 获取对象的哈希值  add by geping@2021-05-06
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static int GetHashCode<T>(T obj) {
      return JsonConvert.SerializeObject(obj).GetHashCode();
    }
  }
}
